package com.yami.shop.service.impl;

import com.yami.shop.common.bean.WxMiniApp;
import com.yami.shop.common.config.WxMaConfig;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.service.WxMaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序服务实现
 */
@Service
@Slf4j
public class WxMaServiceImpl implements WxMaService {
    
    @Resource
    private WxMaConfig wxMaConfig;
    
    @Resource
    private ShopConfig shopConfig;
    
    @Resource
    private RestTemplate restTemplate;
    
    /**
     * 获取小程序码（适用于需要的码数量较少的业务场景）
     */
    @Override
    public ResponseEntity<Map<String, Object>> getWxacode(String page, String scene, Integer width, 
                                                        Boolean autoColor, String lineColor, Boolean isHyaline) {
        try {
            // 获取小程序访问令牌
            String accessToken = getAccessToken();
            
            // 构建请求URL
            String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
            
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("path", page + "?scene=" + scene);
            
            if (width != null) {
                params.put("width", width);
            }
            
            if (autoColor != null) {
                params.put("auto_color", autoColor);
            }
            
            if (lineColor != null) {
                Map<String, Object> lineColorMap = new HashMap<>();
                String[] colors = lineColor.split(",");
                if (colors.length == 3) {
                    lineColorMap.put("r", Integer.parseInt(colors[0]));
                    lineColorMap.put("g", Integer.parseInt(colors[1]));
                    lineColorMap.put("b", Integer.parseInt(colors[2]));
                    params.put("line_color", lineColorMap);
                }
            }
            
            if (isHyaline != null) {
                params.put("is_hyaline", isHyaline);
            }
            
            // 发送请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class);
            
            // 处理响应
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                byte[] body = responseEntity.getBody();
                
                // 检查是否返回了JSON错误信息
                String bodyStr = new String(body);
                if (bodyStr.contains("errcode")) {
                    log.error("获取小程序码失败: {}", bodyStr);
                    throw new YamiShopBindException("获取小程序码失败: " + bodyStr);
                }
                
                // 将图片转为Base64编码
                String base64Image = Base64.getEncoder().encodeToString(body);
                
                Map<String, Object> result = new HashMap<>();
                result.put("base64Image", base64Image);
                result.put("page", page);
                result.put("scene", scene);
                
                return ResponseEntity.ok(result);
            } else {
                log.error("获取小程序码失败，状态码: {}", responseEntity.getStatusCodeValue());
                throw new YamiShopBindException("获取小程序码失败，状态码: " + responseEntity.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("获取小程序码异常: {}", e.getMessage(), e);
            throw new YamiShopBindException("获取小程序码异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取小程序码（适用于需要的码数量极多的业务场景）
     */
    @Override
    public ResponseEntity<Map<String, Object>> getWxacodeUnlimit(String page, String scene, Integer width, 
                                                               Boolean autoColor, String lineColor, Boolean isHyaline) {
        try {
            // 获取小程序访问令牌
            String accessToken = getAccessToken();
            
            // 构建请求URL
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("page", page);
            params.put("scene", scene);
            
            if (width != null) {
                params.put("width", width);
            }
            
            if (autoColor != null) {
                params.put("auto_color", autoColor);
            }
            
            if (lineColor != null) {
                Map<String, Object> lineColorMap = new HashMap<>();
                String[] colors = lineColor.split(",");
                if (colors.length == 3) {
                    lineColorMap.put("r", Integer.parseInt(colors[0]));
                    lineColorMap.put("g", Integer.parseInt(colors[1]));
                    lineColorMap.put("b", Integer.parseInt(colors[2]));
                    params.put("line_color", lineColorMap);
                }
            }
            
            if (isHyaline != null) {
                params.put("is_hyaline", isHyaline);
            }
            
            // 发送请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class);
            
            // 处理响应
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                byte[] body = responseEntity.getBody();
                
                // 检查是否返回了JSON错误信息
                String bodyStr = new String(body);
                if (bodyStr.contains("errcode")) {
                    log.error("获取小程序码失败: {}", bodyStr);
                    throw new YamiShopBindException("获取小程序码失败: " + bodyStr);
                }
                
                // 将图片转为Base64编码
                String base64Image = Base64.getEncoder().encodeToString(body);
                
                Map<String, Object> result = new HashMap<>();
                result.put("base64Image", base64Image);
                result.put("page", page);
                result.put("scene", scene);
                
                return ResponseEntity.ok(result);
            } else {
                log.error("获取小程序码失败，状态码: {}", responseEntity.getStatusCodeValue());
                throw new YamiShopBindException("获取小程序码失败，状态码: " + responseEntity.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("获取小程序码异常: {}", e.getMessage(), e);
            throw new YamiShopBindException("获取小程序码异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取小程序二维码（适用于需要的码数量较少的业务场景）
     */
    @Override
    public ResponseEntity<Map<String, Object>> createWxaQrcode(String path, Integer width) {
        try {
            // 获取小程序访问令牌
            String accessToken = getAccessToken();
            
            // 构建请求URL
            String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
            
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("path", path);
            
            if (width != null) {
                params.put("width", width);
            }
            
            // 发送请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class);
            
            // 处理响应
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                byte[] body = responseEntity.getBody();
                
                // 检查是否返回了JSON错误信息
                String bodyStr = new String(body);
                if (bodyStr.contains("errcode")) {
                    log.error("获取小程序二维码失败: {}", bodyStr);
                    throw new YamiShopBindException("获取小程序二维码失败: " + bodyStr);
                }
                
                // 将图片转为Base64编码
                String base64Image = Base64.getEncoder().encodeToString(body);
                
                Map<String, Object> result = new HashMap<>();
                result.put("base64Image", base64Image);
                result.put("path", path);
                
                return ResponseEntity.ok(result);
            } else {
                log.error("获取小程序二维码失败，状态码: {}", responseEntity.getStatusCodeValue());
                throw new YamiShopBindException("获取小程序二维码失败，状态码: " + responseEntity.getStatusCodeValue());
            }
        } catch (Exception e) {
            log.error("获取小程序二维码异常: {}", e.getMessage(), e);
            throw new YamiShopBindException("获取小程序二维码异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取小程序访问令牌
     */
    private String getAccessToken() {
        // 使用ShopConfig获取微信小程序配置
        WxMiniApp wxMiniApp = shopConfig.getWxMiniApp();
        String appid = wxMiniApp.getAppId();
        String secret = wxMiniApp.getSecret();
        
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> body = responseEntity.getBody();
            if (body != null && body.containsKey("access_token")) {
                return (String) body.get("access_token");
            } else {
                log.error("获取小程序访问令牌失败: {}", body);
                throw new YamiShopBindException("wxma.accessTokenFailed");
            }
        } else {
            log.error("获取小程序访问令牌失败，状态码: {}", responseEntity.getStatusCodeValue());
            throw new YamiShopBindException("wxma.accessTokenFailed");
        }
    }
} 